package com.engc.common.controller;

import java.awt.Color;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.engc.common.bean.SqlBean;
import com.engc.common.bean.SysUserInfo;
import com.engc.common.cache.CacheManager;
import com.engc.common.dao.DBExecuteException;
import com.engc.common.service.BaseService;
import com.engc.common.utils.BaseUtils;
import com.engc.common.utils.Constant;
import com.engc.common.utils.DateUtil;
import com.engc.common.utils.ExcelTemplate;
import com.engc.common.utils.FilterGroup;
import com.engc.common.utils.FilterTranslator;
import com.engc.common.utils.MD5Util;
import com.engc.common.utils.MessageManager;
import com.lowagie.text.Cell;
import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Section;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.rtf.RtfWriter2;

@Controller
@RequestMapping("/SystemWeb")
public class SystemWeb {

	private MessageManager env = new MessageManager("env");

	@Resource
	private BaseService baseService;

	/**
	 * 系统获取Tree
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getTree")
	@ResponseBody
	public List<Map<String, Object>> getTree(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String view = req.getParameter("view");
		String where = req.getParameter("where");
		String idfield = req.getParameter("idfield");
		String pidfield = req.getParameter("pidfield");
		String textfield = req.getParameter("textfield");
		String iconfield = req.getParameter("iconfield") == null ? "" : req.getParameter("iconfield");
		String iconroot = req.getParameter("iconroot");
		String root = req.getParameter("root") == null ? "" : req.getParameter("root");
		String rooticon = req.getParameter("rooticon");
		StringBuffer sb = new StringBuffer();
		StringBuffer field = new StringBuffer();
		field.append(textfield).append(" as text");
		if (!BaseUtils.isEmpty(idfield)) {
			field.append(",").append(idfield).append(",").append(idfield).append(" as id");
		}
		if (!BaseUtils.isEmpty(pidfield)) {
			field.append(",").append(pidfield).append(",").append(pidfield).append(" as parent");
		}
		if (!BaseUtils.isEmpty(iconfield)) {
			field.append(",").append("'" + iconroot + "'").append("||").append(iconfield).append(" as icon");
		}
		String whereSql = " 1=1 ";
		Object[] parameter = null;
		FilterGroup wheres = null;
		FilterTranslator translator = null;
		if (where != null && !"".equals(where)) {
			wheres = JSON.parseObject(where, FilterGroup.class);
			translator = new FilterTranslator(wheres);
		}

		if (translator != null && wheres != null) {
			whereSql = translator.TranslateGroup(wheres, " ");
			parameter = translator.getParameters();
		}
		String SQL = sb.append("SELECT ").append(field).append(" FROM ").append(view).append(" WHERE ").append(whereSql).toString();
		List<Map<String, Object>> treeData = baseService.Query(SQL, parameter);
		List<Map<String, Object>> tempTree = BaseUtils.ArrayToTreeData(treeData, idfield.toLowerCase(), pidfield.toLowerCase());
		List<Map<String, Object>> rsTree = new ArrayList<Map<String, Object>>();
		if (!BaseUtils.isEmpty(root)) {
			Map<String, Object> rootTree = new HashMap<String, Object>();
			rootTree.put("text", root);
			rootTree.put("icon", rooticon);
			rootTree.put("children", tempTree);
			rsTree.add(rootTree);
		} else {
			rsTree = tempTree;
		}
		return rsTree;
	}

	/**
	 * 系统获取Tree(zTree框架获取)
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getZTree")
	@ResponseBody
	public List<Map<String, Object>> getZTree(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String view = req.getParameter("view");
		String where = req.getParameter("where");
		String idfield = req.getParameter("idfield");
		String pidfield = req.getParameter("pidfield");
		String textfield = req.getParameter("textfield");
		String iconfield = req.getParameter("iconfield") == null ? "" : req.getParameter("iconfield");
		String iconroot = req.getParameter("iconroot");
		StringBuffer sb = new StringBuffer();
		StringBuffer field = new StringBuffer();
		field.append(textfield).append(" as name");
		if (!BaseUtils.isEmpty(idfield)) {
			field.append(",").append(idfield).append(" as id");
		}
		if (!BaseUtils.isEmpty(pidfield)) {
			field.append(",").append(pidfield).append(" as pId");
		}
		if (!BaseUtils.isEmpty(iconfield)) {
			field.append(",").append("'" + iconroot + "'").append("||").append(iconfield).append(" as icon");
		}
		String whereSql = " 1=1 ";
		Object[] parameter = null;
		if (where != null && !"".equals(where)) {
			FilterGroup wheres = JSON.parseObject(where, FilterGroup.class);
			FilterTranslator translator = new FilterTranslator(wheres);
			whereSql = translator.TranslateGroup(wheres, " ");
			parameter = translator.getParameters();
		}
		String SQL = sb.append("SELECT ").append(field).append(" FROM ").append(view).append(" WHERE ").append(whereSql).toString();
		List<Map<String, Object>> treeData = baseService.Query(SQL, parameter);

		return treeData;
	}

	/**
	 * 获取Grid 数据 基类
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getGrid")
	@ResponseBody
	public Map<String, Object> getGrid(HttpServletRequest req, HttpServletResponse resp) {

		try {

			String view = req.getParameter("view"); // 表名 单表查询
			String resource = req.getParameter("resource"); // 资源名

			String sortname = req.getParameter("sortname"); // 排序列名
			String sortorder = req.getParameter("sortorder");
			String _pagenumber = req.getParameter("page");
			String _pagesize = req.getParameter("pagesize");
			String where = req.getParameter("where"); // 查询条件
			String where2 = req.getParameter("where2");// 数据权限
			SysUserInfo user = BaseUtils.getCurrentUser(req);
			int pagenumber = 1, pagesize = 0;
			// 可分页
			if (!BaseUtils.isEmpty(_pagenumber) && !BaseUtils.isEmpty(_pagesize)) {
				pagenumber = Integer.valueOf(_pagenumber);
				pagesize = Integer.valueOf(_pagesize);
				if (pagesize == 0)
					pagesize = 20;
			}
			// 可排序
			if (!BaseUtils.isEmpty(sortname)) {
				sortorder = BaseUtils.isEmpty(sortorder) || "asc".equals(sortorder) ? "asc" : "desc";
			}
			String whereSql = " 1=1 ";
			Object[] parameter = null;
			FilterGroup wheres = null;
			FilterTranslator translator = null;
			if (!StringUtils.isBlank(where)) {
				wheres = JSON.parseObject(where, FilterGroup.class);
			}

			if (!StringUtils.isBlank(where2)) {
				wheres = BaseUtils.getRuleGroup(wheres, JSON.parseObject(where2, FilterGroup.class));
			}

			translator = new FilterTranslator(wheres);
			translator.setUser(user);

			String sql = "";
			String countsql = "";

			if (!BaseUtils.isEmpty(view)) {
				StringBuffer sb = new StringBuffer();
				StringBuffer countsqlBuf = new StringBuffer();
				if (translator != null && wheres != null) {
					whereSql = translator.TranslateGroup(wheres, " ");
					parameter = translator.getParameters();
				}
				sb.append("SELECT * FROM ").append(view).append(" WHERE ").append(whereSql);
				countsqlBuf.append("SELECT COUNT(1) FROM ").append(view).append("  WHERE  ").append(whereSql);
				if (!BaseUtils.isEmpty(sortname)) {
					sb.append(" ORDER BY ").append(sortname).append(" ").append(sortorder);
				}
				sql = sb.toString();
				countsql = countsqlBuf.toString();
			}
			// 以复杂SQL作为优先级最高
			if (!BaseUtils.isEmpty(resource)) {
				SqlBean sqlbean = (SqlBean) CacheManager.get("sqlConfigs", resource);
				if (sqlbean != null) {
					String aline = "EDHDGSK";
					StringBuffer sb = new StringBuffer();
					StringBuffer countsqlBuf = new StringBuffer();
					if (translator != null && wheres != null) {
						whereSql = translator.TranslateGroup(wheres, aline + ".");
						parameter = translator.getParameters();
					}
					sb.append("select * from (" + replaceBlank(sqlbean.getSql()) + " ) " + aline).append("  WHERE ").append(whereSql);
					countsqlBuf.append("select count(1) from (" + replaceBlank(sqlbean.getSql()) + " ) " + aline).append(" WHERE ").append(whereSql);
					if (!BaseUtils.isEmpty(sortname)) {
						sb.append(" ORDER BY ").append(aline).append(".").append(sortname).append("  ").append(sortorder);
					}
					sql = sb.toString();
					countsql = countsqlBuf.toString();
				} else {
					return BaseUtils.getGridData(0, new ArrayList());
				}
			}

			if(StringUtils.isBlank(sql)){
				throw new Exception("view and resourcr are all empty ...");
			}
			
			int Total = baseService.executeCountSql(countsql, parameter);
			List<Map<String, Object>> gridData = new ArrayList<Map<String, Object>>();
			if (Total > 0) {
				gridData = baseService.Query(sql, parameter);
			}
			return BaseUtils.getGridData(Total, gridData);
		} catch (Exception e) {
			e.printStackTrace();
			return BaseUtils.getGridData(0, null);
		}
	}

	/**
	 * 导出Excel文件
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/exportExcel")
	public void ExportExcel(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		String view = req.getParameter("view"); // 表名 单表查询
		String resource = req.getParameter("resource"); // 资源名 ，sql名，sqlConfig
														// xml 文件中配置的Sql名称
		String sortname = req.getParameter("sortname"); // 排序列名
		String sortorder = req.getParameter("sortorder");
		String _pagenumber = req.getParameter("page");
		String _pagesize = req.getParameter("pagesize");
		String where = req.getParameter("where");
		String title = req.getParameter("title"); //标题
		String sheetName = req.getParameter("sheetName"); // 子标题
		String filename = req.getParameter("filename"); //文件名
		String columns = new String(req.getParameter("columns").getBytes("utf8"));
		SysUserInfo user = BaseUtils.getCurrentUser(req);
		int pagenumber = 1, pagesize =  99999;
		where = Pattern.compile("\t|\r|\n| \\|").matcher(where).replaceAll("");
		// 可分页
		if (!BaseUtils.isEmpty(_pagenumber) && !BaseUtils.isEmpty(_pagesize)) {
			pagenumber = Integer.valueOf(_pagenumber);
			pagesize = Integer.valueOf(_pagesize);
			if (pagesize == 0)
				pagesize = 99999;
		}
		// 可排序
		if (!BaseUtils.isEmpty(sortname)) {
			sortorder = BaseUtils.isEmpty(sortorder) || "asc".equals(sortorder) ? "asc"
					: "desc";
		}
		String whereSql = " 1=1 ";
		Object[] parameter = null;
		FilterTranslator translator = null;
		FilterGroup wheres = null;
		if (!BaseUtils.isEmpty(where)) {
			wheres = JSON.parseObject(where, FilterGroup.class);
			translator = new FilterTranslator(wheres);
			translator.setUser(user);
		}
		String sql = "";

		if (!BaseUtils.isEmpty(view)) {
			StringBuffer sb = new StringBuffer();
			if (translator != null && wheres != null) {
				whereSql = translator.TranslateGroup(wheres, " ");
				parameter = translator.getParameters();
			}
			sb.append("SELECT * FROM ").append(view).append(" WHERE ")
					.append(whereSql);
			if (!BaseUtils.isEmpty(sortname)) {
				sb.append(" ORDER BY ").append(sortname).append(" ")
						.append(sortorder);
			}
			sql = sb.toString();
		}
		// 以复杂SQL作为优先级最高
		if (!BaseUtils.isEmpty(resource)) {
			SqlBean sqlbean = (SqlBean) CacheManager
					.get("sqlConfigs", resource);
			if (sqlbean != null) {
				String aline = "EDHDGSK";
				StringBuffer sb = new StringBuffer();
				if (translator != null && wheres != null) {
					whereSql = translator.TranslateGroup(wheres, aline + ".");
					parameter = translator.getParameters();
				}
				sb.append(
						"select * from (" + replaceBlank(sqlbean.getSql())
								+ " ) " + aline).append(" WHERE ")
						.append(whereSql);
				if (!BaseUtils.isEmpty(sortname)) {
					sb.append(" ORDER BY ").append(aline).append(".")
							.append(sortname).append(" ").append(sortorder);
				}
				sql = sb.toString();
			} 
		}
		List<Map> mycolumns = new ArrayList<Map>();
		if(!BaseUtils.isEmpty(columns)){
			mycolumns = JSON.parseArray(columns, Map.class);
		}
		List<Map<String, Object>> gridData = baseService.Query_SliceOracle(sql, pagenumber, pagesize,
					parameter);
		ExcelTemplate et = ExcelTemplate.newInstance();
		Properties p = new Properties();
		if(!BaseUtils.isEmpty(title)){
			p.put("Title", title);
			et.setCellStyle("STYLE_Title");
			et.MergedRegion(0, 0, 1, mycolumns.size()-1);
			et.setCellDefaultStyle();
		}
		if(!BaseUtils.isEmpty(sheetName)){
			et.setSheetName(sheetName);
		}
		et.createRow(0);
		//设置Excel 列名
		
		for(Map<String,Object> gridcon:mycolumns){
			if(gridcon.get("display")!=null&&gridcon.get("name")!=null){
				et.setCellStyle("STYLE_ColumnName");
				et.createCell(gridcon.get("display").toString());
				et.setCellDefaultStyle();
			}
		}
		int i=1;
		if(gridData!=null&&!gridData.isEmpty()){
			for(Map<String, Object> data:gridData){
				et.createRow(i);
				for(int k=0;k<mycolumns.size();k++)
				{
					Map temp = mycolumns.get(k);
					if(temp.get("display")!=null&&temp.get("name")!=null){
						Object columnname = temp.get("name");
						et.createCell(data.get(columnname)==null?"":data.get(columnname).toString());
					}
				}
				i+=1;
			}
		}
		et.replaceParameters(p);
		int j=0;
		for(Map<String,Object> gridcon:mycolumns){
			if(gridcon.get("width")!=null&&!"auto".equals(gridcon.get("width"))){
				String widthstr = gridcon.get("width").toString();
				int width = 	Integer.valueOf(widthstr);
				et.setCellWidth(j, width);
			}
			j++;
		}
		
		HSSFWorkbook wb = et.getWorkbook();
		//提供下载
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		filename = BaseUtils.isEmpty(filename)?df.format(new Date()):filename;
		resp.reset();
		resp.setContentType("application/x-download;charset=UTF-8");
		resp.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes("UTF-8"), "iso8859-1")+".xls");
		//resp.setContentType("application/vnd.ms-excel;charset=UTF-8");
		//resp.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes("gb2312"),"ISO8859-1")+".xls");
		try {
			et.getWorkbook().write(resp.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 导出表格数据
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/exportGridData")
	public void exportGridData(HttpServletRequest req, HttpServletResponse resp) throws Exception {

		try {
			String exportType = req.getParameter("exportType"); // 导出类型
			String title = req.getParameter("title"); // 标题
			String sheetName = req.getParameter("sheetName"); // 子标题
			String filename = req.getParameter("filename"); // 文件名
			String columns = req.getParameter("columns");
			String countColumn = req.getParameter("countColumn");

			DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			filename = BaseUtils.isEmpty(filename) ? df.format(new Date()) : filename;

			List<Map> mycolumns = new ArrayList<Map>();
			if (!BaseUtils.isEmpty(columns)) {
				mycolumns = JSON.parseArray(columns, Map.class);
			}

			String hidecolumn = req.getParameter("hideColumn");
			if (StringUtils.isNotBlank(hidecolumn)) {
				List<String> hideLs = JSON.parseArray(hidecolumn, String.class);

				int len = mycolumns.size();
				for (int i = len - 1; i >= 0; i--) {
					if (mycolumns.get(i).get("name") == null || hideLs.contains(String.valueOf(mycolumns.get(i).get("name")))) {
						mycolumns.remove(i);
					}
				}
			}
			Map<String, Long> countMap = null;
			List<String> countColumnLs = new ArrayList<String>();
			if (StringUtils.isNotBlank(countColumn)) {
				countColumnLs = JSON.parseArray(countColumn, String.class);// 计算总和的列
				countMap = new HashMap<String, Long>();
				for (String s : countColumnLs) {
					countMap.put(s, 0L);
				}
			}

			String view = req.getParameter("view"); // 表名 单表查询
			String resource = req.getParameter("resource"); // 资源名
			String sortname = req.getParameter("sortname"); // 排序列名
			String sortorder = req.getParameter("sortorder");
			String where = req.getParameter("where"); // 查询条件
			String where2 = req.getParameter("where2");// 数据权限
			SysUserInfo user = BaseUtils.getCurrentUser(req);

			where = Pattern.compile("\t|\r|\n| \\|").matcher(where).replaceAll("");
			where2 = Pattern.compile("\t|\r|\n| \\|").matcher(where2).replaceAll("");

			// 可排序
			if (!BaseUtils.isEmpty(sortname)) {
				sortorder = BaseUtils.isEmpty(sortorder) || "asc".equals(sortorder) ? "asc" : "desc";
			}
			String whereSql = " 1=1 ";
			Object[] parameter = null;
			FilterGroup wheres = null;
			FilterTranslator translator = null;
			if (!StringUtils.isBlank(where)) {
				wheres = JSON.parseObject(where, FilterGroup.class);
			}
			if (!StringUtils.isBlank(where2)) {
				wheres = BaseUtils.getRuleGroup(wheres, JSON.parseObject(where2, FilterGroup.class));
			}
			translator = new FilterTranslator(wheres);
			translator.setUser(user);

			String sql = "";

			if (!BaseUtils.isEmpty(view)) {
				StringBuffer sb = new StringBuffer();
				if (translator != null && wheres != null) {
					whereSql = translator.TranslateGroup(wheres, " ");
					parameter = translator.getParameters();
				}
				sb.append("SELECT * FROM ").append(view).append(" WHERE ").append(whereSql);
				if (!BaseUtils.isEmpty(sortname)) {
					sb.append(" ORDER BY ").append(sortname).append(" ").append(sortorder);
				}
				sql = sb.toString();
			}
			if (!BaseUtils.isEmpty(resource)) {
				SqlBean sqlbean = (SqlBean) CacheManager.get("sqlConfigs", resource);
				if (sqlbean != null) {
					String aline = "EDHDGSK";
					StringBuffer sb = new StringBuffer();
					if (translator != null && wheres != null) {
						whereSql = translator.TranslateGroup(wheres, aline + ".");
						parameter = translator.getParameters();
					}
					sb.append("select * from (" + replaceBlank(sqlbean.getSql()) + " ) " + aline).append(" WHERE ").append(whereSql);
					if (!BaseUtils.isEmpty(sortname)) {
						sb.append(" ORDER BY ").append(aline).append(".").append(sortname).append(" ").append(sortorder);
					}
					sql = sb.toString();
				} else {
					throw new Exception("资源文件不存在");
				}
			}

			List<Map<String, Object>> gridData = baseService.Query(sql, parameter);

			if (exportType.equals("excel")) {

				ExcelTemplate et = ExcelTemplate.newInstance();
				Properties p = new Properties();
				if (!BaseUtils.isEmpty(title)) {
					p.put("Title", title);
					et.setCellStyle("STYLE_Title");
					et.MergedRegion(0, 0, 1, mycolumns.size() - 1);
					et.setCellDefaultStyle();
				}
				if (!BaseUtils.isEmpty(sheetName)) {
					et.setSheetName(sheetName);
				}
				et.createRow(0);

				// 设置Excel 列名
				for (Map<String, Object> gridcon : mycolumns) {
					if (gridcon.get("display") != null && gridcon.get("name") != null) {
						et.setCellStyle("STYLE_ColumnName");
						et.createCell(gridcon.get("display").toString());
						et.setCellDefaultStyle();
					}
				}

				int i = 1;
				if (gridData != null && !gridData.isEmpty()) {
					for (Map<String, Object> data : gridData) {
						et.createRow(i);
						for (int k = 0; k < mycolumns.size(); k++) {
							Map temp = mycolumns.get(k);
							if (temp.get("display") != null && temp.get("name") != null) {

								Object columnname = temp.get("name");
								et.createCell(data.get(columnname) == null ? "" : data.get(columnname).toString());
								if (countColumnLs.contains(String.valueOf(temp.get("name")))) {
									countMap.put(
											String.valueOf(temp.get("name")),
											countMap.get(String.valueOf(temp.get("name")))
													+ Long.parseLong(data.get(columnname) == null ? "0" : data.get(columnname).toString()));
								}
							}
						}
						i += 1;
					}
				}

				// 统计列
				et.createRow(i);
				for (int k = 0; k < mycolumns.size(); k++) {
					Map temp = mycolumns.get(k);
					if (temp.get("display") != null && temp.get("name") != null && countColumnLs.contains(String.valueOf(temp.get("name")))) {

						et.createCell("总计：" + countMap.get(String.valueOf(temp.get("name"))));
					} else {
						et.createCell("");
					}
				}

				et.replaceParameters(p);
				int j = 0;
				for (Map<String, Object> gridcon : mycolumns) {
					if (gridcon.get("width") != null && !"auto".equals(gridcon.get("width"))) {
						String widthstr = gridcon.get("width").toString();
						int width = 0;
						try {
							width = Integer.valueOf(widthstr);
						} catch (Exception e) {
							e.printStackTrace();
							width = 200;
						}

						et.setCellWidth(j, width);
					}
					j++;
				}

				// 提供下载

				resp.reset();
				resp.setContentType("application/x-download;charset=UTF-8");
				
				setFileDownloadHeader(req, resp, filename+".xls");
				//resp.setHeader("Content-Disposition", "attachment;filename=" + toUtf8String(filename) + ".xls");

				et.getWorkbook().write(resp.getOutputStream());

			} else if (exportType.equals("word")) {

				File wordFile = this.createDocFile(gridData, mycolumns, countColumnLs, countMap, env.getMessage("server_cvs_path"), title);
				try {
					int read = 0;
					byte[] bytes = new byte[1024 * 100];

					resp.setContentType("image/x-dcx;charset=utf-8");
					//resp.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(filename, "utf-8") + ".doc");
					setFileDownloadHeader(req, resp, wordFile.getName());
					FileInputStream fis = new FileInputStream(new File(wordFile.getPath()));
					ServletOutputStream sos = resp.getOutputStream();
					while ((read = fis.read(bytes)) != -1) {
						sos.write(bytes, 0, read);
					}
					sos.flush();
					sos.close();
				} catch (IOException e) {
					e.printStackTrace();

				}

			} else if (exportType.equals("pdf")) {

				File pdfFile = this.createPDFFile(gridData, mycolumns, countColumnLs, countMap, env.getMessage("server_cvs_path"), title);
				try {
					int read = 0;
					byte[] bytes = new byte[1024 * 100];

					resp.setContentType("application/pdf;charset=utf-8");
					//resp.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(filename, "utf-8") + ".pdf");
					setFileDownloadHeader(req, resp, pdfFile.getName());
					FileInputStream fis = new FileInputStream(new File(pdfFile.getPath()));
					ServletOutputStream sos = resp.getOutputStream();
					while ((read = fis.read(bytes)) != -1) {
						sos.write(bytes, 0, read);
					}
					sos.flush();
					sos.close();
				} catch (IOException e) {
					e.printStackTrace();

				}

			} else if (exportType.equals("csv")) {

				// 生成本地文件
				File exportFile = this.createCSVFile(gridData, mycolumns, countColumnLs, countMap, env.getMessage("server_cvs_path"), title);

				try {
					int read = 0;
					byte[] bytes = new byte[1024 * 100];

					resp.setContentType("application/csv;charset=utf-8");
					//resp.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(exportFile.getName(), "utf-8") + "\"");
					setFileDownloadHeader(req, resp, exportFile.getName());
					FileInputStream fis = new FileInputStream(new File(exportFile.getPath()));
					ServletOutputStream sos = resp.getOutputStream();
					while ((read = fis.read(bytes)) != -1) {
						sos.write(bytes, 0, read);
					}
					sos.flush();
					sos.close();
				} catch (IOException e) {
					e.printStackTrace();

				}
			} else {
				System.out.println("不支持的类型");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public File createPDFFile(List<Map<String, Object>> exportData, List<Map> mycolumns, List<String> countColumnLs, Map<String, Long> countMap,
			String outPutPath, String titlename) throws Exception {

		Font font = new Font(BaseFont.createFont("simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED));

		String dateStr = DateUtil.sampleTimeFormat(new Date());
		File pdfFile = new File(outPutPath + "/" + titlename + ".pdf");
		File parent = pdfFile.getParentFile();
		if (parent != null && !parent.exists()) {
			parent.mkdirs();
		}

		Document document = new Document(PageSize.A4, 50, 50, 50, 50);
		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
		document.open();

		Paragraph paragraph = new Paragraph("数据导出", font);

		Chapter chapter1 = new Chapter(paragraph, 1);
		chapter1.setNumberDepth(1);

		Paragraph title11 = new Paragraph(titlename, font);
		
		Section section1 = chapter1.addSection(title11);

		PdfPTable t = new PdfPTable(mycolumns.size());

		t.setSpacingBefore(25);
		t.setSpacingAfter(25);

		for (Map column : mycolumns) {
			t.addCell(new PdfPCell(new Phrase(String.valueOf(column.get("display")), font)));
		}

		for (Map<String, Object> rowData : exportData) {
			for (Map column : mycolumns) {
				t.addCell(new PdfPCell(new Phrase(rowData.get(column.get("name"))==null ? "":String.valueOf(rowData.get(column.get("name"))), font)));
				// t.addCell(String.valueOf(rowData.get(column.get("name"))));
				if (countColumnLs.contains(String.valueOf(column.get("name")))) {
					countMap.put(
							String.valueOf(column.get("name")),
							countMap.get(String.valueOf(column.get("name")))
									+ Long.parseLong(rowData.get(column.get("name")) == null ? "0" : String.valueOf(rowData.get(column.get("name")))));
				}
			}
		}
		
		
		if(countColumnLs!=null && !countColumnLs.isEmpty()){
			for (Map column : mycolumns) {
				if (countColumnLs.contains(String.valueOf(column.get("name")))) {
					t.addCell(new PdfPCell(new Phrase("总计：" + String.valueOf(countMap.get(String.valueOf(column.get("name")))), font)));
				} else {
					t.addCell(new PdfPCell(new Phrase("", font)));
				}
			}

		}
		
		//section1.add(t);
		//document.add(chapter1);
		
		document.add(t);
		document.close();
		writer.flush();
		writer.close();

		return pdfFile;

	}

	public File createDocFile(List<Map<String, Object>> exportData, List<Map> mycolumns, List<String> countColumnLs, Map<String, Long> countMap,
			String outPutPath, String titlename) throws Exception {

		String dateStr = DateUtil.sampleTimeFormat(new Date());
		File docFile = new File(outPutPath + "/" + titlename  + ".doc");
		File parent = docFile.getParentFile();
		if (parent != null && !parent.exists()) {
			parent.mkdirs();
		}

		Font font = new Font(BaseFont.createFont("simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED));
		// 创建word文档,并设置纸张的大小
		Document document = new Document(PageSize.A4);

		RtfWriter2.getInstance(document, new FileOutputStream(docFile));

		document.open();

		// 设置合同头
		Paragraph ph = new Paragraph();
		Font f = new Font();

		Paragraph p = new Paragraph(titlename, font);
		p.setAlignment(1);
		document.add(p);
		ph.setFont(f);

		/*
		 * 创建表格
		 */
		Table table = new Table(mycolumns.size());
		document.add(new Paragraph(""));
		table.setBorderWidth(1);
		table.setBorderColor(Color.BLACK);
		table.setPadding(0);
		table.setSpacing(0);

		/*
		 * 添加表头的元素
		 */

		for (Map column : mycolumns) {
			table.addCell(new Cell(String.valueOf(column.get("display"))));
		}
		table.endHeaders();// 表头结束

		for (Map<String, Object> rowData : exportData) {
			for (Map column : mycolumns) {
				table.addCell(new Paragraph(rowData.get(column.get("name"))==null ? "":String.valueOf(rowData.get(column.get("name"))), font));
				if (countColumnLs.contains(String.valueOf(column.get("name")))) {
					countMap.put(
							String.valueOf(column.get("name")),
							countMap.get(String.valueOf(column.get("name")))
									+ Long.parseLong(rowData.get(column.get("name")) == null ? "0" : String.valueOf(rowData.get(column.get("name")))));
				}
			}
		}

		if(countColumnLs!=null && !countColumnLs.isEmpty()){
			for (Map column : mycolumns) {
				if (countColumnLs.contains(String.valueOf(column.get("name")))) {
					table.addCell(new Paragraph("总计：" + String.valueOf(countMap.get(String.valueOf(column.get("name")))), font));
				} else {
					table.addCell(new Paragraph("", font));
				}
			}
		}
		

		document.add(table);
		document.close();

		return docFile;

	}

	public File createCSVFile(List<Map<String, Object>> exportData, List<Map> mycolumns, List<String> countColumnLs, Map<String, Long> countMap,
			String outPutPath, String filename) {

		// String dateStr = DateUtil.sampleTimeFormat(new Date());
		File csvFile = null;
		BufferedWriter csvFileOutputStream = null;
		try {
			csvFile = new File(outPutPath + filename + ".csv");
			// csvFile.getParentFile().mkdirs();
			File parent = csvFile.getParentFile();
			if (parent != null && !parent.exists()) {
				parent.mkdirs();
			}
			csvFile.createNewFile();

			// GB2312使正确读取分隔符","
			csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);
			// 写入文件头部
			int columncount = mycolumns.size();
			Map columnMap = null;
			for (int i = 0; i < columncount; i++) {
				columnMap = mycolumns.get(i);
				csvFileOutputStream.write("\"" + columnMap.get("display") + "\"");
				if (i < columncount - 1) {
					csvFileOutputStream.write(",");
				}
			}
			csvFileOutputStream.newLine();

			// 写入文件内容
			String name = null;
			for (Map<String, Object> rowData : exportData) {
				for (int i = 0; i < columncount; i++) {
					name = (String) mycolumns.get(i).get("name");
					csvFileOutputStream.write("\"" + (rowData.get(name)==null ? "":rowData.get(name)) + "\"");
					if (i < columncount - 1) {
						csvFileOutputStream.write(",");
					}
					if (countColumnLs.contains(name)) {
						countMap.put(String.valueOf(name),
								countMap.get(name) + Long.parseLong(rowData.get(name) == null ? "0" : String.valueOf(rowData.get(name))));
					}

				}
				csvFileOutputStream.newLine();
			}

			for (int k = 0; k < mycolumns.size(); k++) {
				Map temp = mycolumns.get(k);
				if (temp.get("display") != null && temp.get("name") != null && countColumnLs.contains(String.valueOf(temp.get("name")))) {
					csvFileOutputStream.write("\"总计：" + countMap.get(String.valueOf(temp.get("name"))) + "\"");
				} else {
					csvFileOutputStream.write(" ");
				}
				if (k < columncount - 1) {
					csvFileOutputStream.write(",");
				}
			}

			csvFileOutputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				csvFileOutputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return csvFile;
	}

	public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}

	/**
	 * 获取所有图标
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getIcons")
	@ResponseBody
	public Map<String, Object> getIcons(HttpServletRequest request) {
		String rootPath = request.getRealPath("/resource/icons/32X32");
		List<String> files = this.getFiles(rootPath);
		return BaseUtils.getSuccessMessage(files);
	}

	/**
	 * 获取TreeGrid 权限
	 * 
	 * @param request
	 */
	@RequestMapping("/getTreeGrid")
	@ResponseBody
	public Map<String, Object> getTreeGrid(HttpServletRequest request) {
		String view = request.getParameter("view");
		String where = request.getParameter("where");
		String where2 = request.getParameter("where2");
		String idfield = request.getParameter("idfield");
		String pidfield = request.getParameter("pidfield");
		StringBuffer sb = new StringBuffer();
		String whereSql = " 1=1 ";
		Object[] parameter = null;
		FilterGroup wheres = null;
		FilterTranslator translator = null;
		
		
		if (!StringUtils.isBlank(where)) {
			wheres = JSON.parseObject(where, FilterGroup.class);
		}
		if (!StringUtils.isBlank(where2)) {
			wheres = BaseUtils.getRuleGroup(wheres, JSON.parseObject(where2, FilterGroup.class));
		}
		if (where != null && !"".equals(where)) {
			wheres = JSON.parseObject(where, FilterGroup.class);
			translator = new FilterTranslator(wheres);
		}
		

		if (translator != null && wheres != null) {
			whereSql = translator.TranslateGroup(wheres, " ");
			parameter = translator.getParameters();
		}
		String SQL = sb.append("SELECT * FROM ").append(view).append(" WHERE ").append(whereSql).toString();
		int Total = baseService.getTotal(view, whereSql, parameter);
		List<Map<String, Object>> tempGridData = new ArrayList<Map<String, Object>>();
		if (Total > 0) {
			List<Map<String, Object>> treeData = baseService.Query(SQL, parameter);
			tempGridData = BaseUtils.ArrayToTreeData(treeData, idfield, pidfield);
		}
		return BaseUtils.getGridData(Total, tempGridData);
	}

	/**
	 * 获取TreeGrid 权限,适合多表查询
	 * 
	 * @param request
	 */
	@RequestMapping("/getTreeGrid2")
	@ResponseBody
	public Map<String, Object> getTreeGrid2(HttpServletRequest request) {
		String resource = request.getParameter("resource");
		String where = request.getParameter("where");
		String where2 = request.getParameter("where2");
		String idfield = request.getParameter("idfield");
		String pidfield = request.getParameter("pidfield");
		String _pagenumber = request.getParameter("page");
		String _pagesize = request.getParameter("pagesize");

		SqlBean sqlbean = (SqlBean) CacheManager.get("sqlConfigs", resource);

		StringBuffer sb = new StringBuffer();
		String whereSql = " 1=1";
		Object[] parameter = null;
		FilterGroup wheres = null;
		FilterTranslator translator = null;
		int pagenumber = 1, pagesize =  99999;
		// 可分页
		if (!BaseUtils.isEmpty(_pagenumber) && !BaseUtils.isEmpty(_pagesize)) {
			pagenumber = Integer.valueOf(_pagenumber);
			pagesize = Integer.valueOf(_pagesize);
			if (pagesize == 0)
				pagesize = 99999;
		}
		
		if (!StringUtils.isBlank(where)) {
			wheres = JSON.parseObject(where, FilterGroup.class);
		}
		if (!StringUtils.isBlank(where2)) {
			wheres = BaseUtils.getRuleGroup(wheres, JSON.parseObject(where2, FilterGroup.class));
		}
		
		translator = new FilterTranslator(wheres);
		

		if (translator != null && wheres != null) {
			whereSql = translator.TranslateGroup(wheres, " ");
			parameter = translator.getParameters();
		}
		String SQL = sb.append("SELECT * FROM (").append(sqlbean.getSql()).append(") WHERE ").append(whereSql).toString();
		int Total = baseService.getTotal(SQL, parameter);
		List<Map<String, Object>> tempGridData = new ArrayList<Map<String, Object>>();
		if (Total > 0) {
			List<Map<String, Object>> treeData = baseService.Query_SliceOracle(SQL, pagenumber, pagesize, parameter);
			tempGridData = BaseUtils.ArrayToTreeData(treeData, idfield, pidfield);
		}
		return BaseUtils.getGridData(Total, tempGridData);
	}

	/**
	 * 获取Select 下来选择框数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getSelect")
	@ResponseBody
	public List<Map<String, Object>> getSelect(HttpServletRequest request) {
		String view = request.getParameter("view");
		String where = request.getParameter("where");
		String idfield = request.getParameter("idfield");
		String textfield = request.getParameter("textfield");
		String distinct = request.getParameter("distinct");
		StringBuffer sb = new StringBuffer();
		String selectStr = "";
		String distinctStr = "";
		if (!BaseUtils.isEmpty(distinct) && !"false".equalsIgnoreCase(distinct)) {
			distinctStr = "distinct";
		}
		if (!BaseUtils.isEmpty(idfield)) {
			selectStr += "," + idfield + " as id";
			selectStr += "," + idfield + " as value";
		}
		if (!BaseUtils.isEmpty(textfield)) {
			selectStr += "," + textfield + " as text";
		}
		selectStr = "".equals(selectStr.trim()) ? "*" : selectStr.substring(1);
		String whereSql = " 1=1 ";
		Object[] parameter = null;
		FilterGroup wheres = null;
		FilterTranslator translator = null;
		if (where != null && !"".equals(where)) {
			wheres = JSON.parseObject(where, FilterGroup.class);
			translator = new FilterTranslator(wheres);
		}

		if (translator != null && wheres != null) {
			whereSql = translator.TranslateGroup(wheres, " ");
			parameter = translator.getParameters();
		}
		String sql = sb.append("SELECT ").append(distinctStr).append(" ").append(selectStr).append(" FROM ").append(view).append(" WHERE ").append(whereSql)
				.toString();
		List<Map<String, Object>> templst = baseService.Query(sql, parameter);
		return templst;
	}

	/**
	 * 获取当前登录人该菜单的菜单按钮
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getMyButtons")
	@ResponseBody
	public Map<String, Object> getMyButtons(HttpServletRequest request) {
		String menuNo = request.getParameter("MenuNo");
		List<Map<String, Object>> mybuttons = BaseUtils.getButtons(request, menuNo);
		return BaseUtils.getSuccessMessage(mybuttons);
	}

	@RequestMapping("/getSystemDict")
	@ResponseBody
	public List<Map<String, Object>> getSystemDict(HttpServletRequest request) {
		String type = request.getParameter("type");
		String sql = "select value as id,value,label as text from sys_dict where type = ?";
		List<Map<String, Object>> record = baseService.Query(sql, type);
		return record;
	}

	@RequestMapping("/getAllSystemDict")
	@ResponseBody
	public Map<String, List<Map<String, Object>>> getAllSystemDict() {
		Map<String, List<Map<String, Object>>> map = new HashMap<String, List<Map<String, Object>>>();
		try {

			String sql = "select value as id,value,label as text,type from sys_dict";
			List<Map<String, Object>> record = baseService.Query(sql);
			List<Map<String, Object>> tempMap = null;
			for (Map<String, Object> temp : record) {
				if (map.containsKey(String.valueOf(temp.get("type")))) {
					map.get(String.valueOf(temp.get("type"))).add(temp);
				} else {
					tempMap = new ArrayList<Map<String, Object>>();
					map.put(String.valueOf(temp.get("type")), tempMap);
					map.get(String.valueOf(temp.get("type"))).add(temp);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 获取当前登录人的各组织机构
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getSelectOrgs")
	@ResponseBody
	public Map<String, List<Map<String, Object>>> getSelectOrgs(HttpServletRequest request) {
		Map<String, List<Map<String, Object>>> map = new HashMap<String, List<Map<String, Object>>>();
		try {
			SysUserInfo userInfo = BaseUtils.getCurrentUser(request);
			String userorg = userInfo.getDataOrgid();
			String sql = "";
			if (StringUtils.isBlank(userorg)) {
				// 登录人是超级管理员-获取区域列表
				sql = "select d.value as value, d.value as id, d.label as text from sys_dict d where d.type = 'areaType' ";
				List<Map<String, Object>> result = baseService.Query(sql, new Object[] {});
				map.put("areacode", result);
			} else if (userorg.length() == Constant.AREA_ORGID_LENGTH) {
				// 登录人是区域管理员-获取学校列表
				// 区域
				sql = "select d.value as value, d.value as id, d.label as text from sys_dict d where d.type = 'areaType' and d.value = ?";
				List<Map<String, Object>> arearesult = baseService.Query(sql, new Object[] { Integer.valueOf(userorg) });
				map.put("areacode", arearesult);
				// 学校
				sql = "select o.orgid as value,o.orgname as text,o.orgid as id from stb_org o where o.areano = ? and o.nodepath = 2 and o.status = 1 ";
				List<Map<String, Object>> result = baseService.Query(sql, new Object[] {Integer.valueOf(userorg)});
				map.put("schoolcode", result);
			} else if (userorg.length() == Constant.SCHOOL_ORGID_LENGTH) {
				// 登录人是学校管理员-获取年级列表
				// 区域
				sql = "select d.value as value, d.label as text,d.value as id from sys_dict d,stb_org o " +
						"where o.areano = d.value and o.status = 1 and o.orgid = ? and d.type = 'areaType'";
				List<Map<String, Object>> arearesult = baseService.Query(sql, new Object[] { userorg});
				map.put("areacode", arearesult);
				// 学校
				sql = "select s.orgid as value, s.orgname as text,s.orgid as id from stb_org s where s.orgid = ? and s.status = 1";
				List<Map<String, Object>> schoolresult = baseService.Query(sql, new Object[] { userorg });
				map.put("schoolcode", schoolresult);
				// 年级
				sql = "select g.orgid as value, g.orgname as text, g.orgid as id from stb_org g where g.fatherorgid = ? and g.nodepath = 3 and g.status = 1";
				List<Map<String, Object>> graderesult = baseService.Query(sql, new Object[] { userorg });
				map.put("gradecode", graderesult);
			} else if (userorg.length() == Constant.CLASS_ORGID_LENGTH) {
				// 登录人是班主任
				sql = "select d.value as value, d.label as text,d.value as id from sys_dict d,stb_org o " +
						"where o.areano = d.value and o.status = 1 and o.orgid = ? and d.type = 'areaType'";
				List<Map<String, Object>> arearesult = baseService.Query(sql, new Object[] { userorg.substring(0, 6)});
				map.put("areacode", arearesult);
				// 学校
				sql = "select s.orgid as value, s.orgname as text,s.orgid as id from stb_org s where s.orgid = ? and s.status = 1";
				List<Map<String, Object>> schoolresult = baseService.Query(sql, new Object[] { userorg.substring(0, 6) });
				map.put("schoolcode", schoolresult);
				// 年级
				sql = "select g.orgid as value, g.orgname as text, g.orgid as id from stb_org g where g.orgid = ? and g.status = 1 and g.nodepath = 3";
				List<Map<String, Object>> graderesult = baseService.Query(sql, new Object[] { userorg.substring(0, 11) });
				map.put("gradecode", graderesult);
				// 班级
				sql = "select c.orgid as value, c.orgname as text, c.orgid as id from stb_org c where c.orgid = ? and c.status = 1 and c.nodepath = 4";
				List<Map<String, Object>> classresult = baseService.Query(sql, new Object[] { userorg });
				map.put("classcode", classresult);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	
	
	/**
	 * 得到学校名称
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getSchools")
	@ResponseBody
	public List<Map<String, Object>> getSchools(HttpServletRequest request) {
		String sqllike = BaseUtils.isEmpty(request.getParameter("key")) ? "" : " and orgname like '%" + request.getParameter("key") + "%'";
		String sql = " select orgid id,orgname text  from stb_org  where nodepath=2 and status=? " + sqllike;
		List<Map<String, Object>> record = baseService.Query(sql,Constant.VALID_YES);
		return record;
	}

	
	
	
	/**
	 * 根据区域获取学校下拉
	 * 
	 * @param request
	 * @param areacode
	 * @return
	 */
	@RequestMapping("/getSchoolByAreacode")
	@ResponseBody
	public List<Map<String, Object>> getSchoolByAreacode(HttpServletRequest request, @RequestParam("areacode") String areacode) {
		String sql = "select t.orgid as id,t.orgname as text,t.orgid as value from stb_org t where t.areano = ? and t.status = 1 and t.nodepath = 2";
		List<Map<String, Object>> record = baseService.Query(sql, new Object[] {areacode});
		return record;
	}

	/**
	 * 根据学校获取年级下拉
	 * 
	 * @param request
	 * @param schoolcode
	 * @return
	 */
	@RequestMapping("/getGradeBySchoolcode")
	@ResponseBody
	public List<Map<String, Object>> getGradeBySchoolcode(HttpServletRequest request, @RequestParam("schoolcode") String schoolcode) {
		String sql = "select t.orgid as id,t.orgname as text,t.orgid as value from stb_org t where t.fatherorgid = ? and t.status = 1 and t.nodepath = 3";
		List<Map<String, Object>> record = baseService.Query(sql, new Object[] { schoolcode });
		return record;
	}

	/**
	 * 根据年级获取班级下拉
	 * 
	 * @param request
	 * @param gradecode
	 * @return
	 */
	@RequestMapping("/getClassByGradecode")
	@ResponseBody
	public List<Map<String, Object>> getClassByGradecode(HttpServletRequest request, @RequestParam("gradecode") String gradecode) {
		String sql = "select t.orgid id,t.orgname text,t.orgid value from stb_org t where t.fatherorgid = ? and t.status = 1 and t.nodepath = 4";
		List<Map<String, Object>> record = baseService.Query(sql, new Object[] { gradecode });
		return record;
	}

	/**
	 * 根据登录人学校获取年级下拉
	 * 
	 * @param request
	 * @param schoolcode
	 * @return
	 */
	@RequestMapping("/getGradeByUserSchoolcode")
	@ResponseBody
	public List<Map<String, Object>> getGradeByUserSchoolcode(HttpServletRequest request) {
		SysUserInfo user = BaseUtils.getCurrentUser(request);
		String schoolcode = user.getOrgid();
		String sql = "select t.orgid as id,t.orgname as text,t.orgid as value from stb_org t where t.fatherorgid = ? and t.status = 1 and t.nodepath = 3";
		List<Map<String, Object>> record = baseService.Query(sql, new Object[] { schoolcode});
		return record;
	}

	@RequestMapping("forwordpage/{folder}/{pages}")
	public String forwordPage(@PathVariable("folder") String folder, @PathVariable("pages") String pages) {
		String page = folder + "/" + pages;
		return page;
	}

	/**
	 * 获取路径下的所有文件
	 * 
	 * @param rootpath
	 * @return
	 */
	private List<String> getFiles(String rootpath) {
		List<String> filelist = new ArrayList<String>();
		File rootfile = new File(rootpath);
		if (rootfile.isFile()) {
			filelist.add(rootfile.getPath());
		}
		if (rootfile.isDirectory()) {
			File[] subfile = rootfile.listFiles();
			for (File file : subfile) {
				filelist.add(file.getPath());
			}
		}
		return filelist;
	}

	/**
	 * 获取当前登录人信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getCurrentUser")
	@ResponseBody
	public Map<String, Object> getCurrentUser(HttpServletRequest request) {
		SysUserInfo user = BaseUtils.getCurrentUser(request);
		Map<String, Object> userinfo = new HashMap<String, Object>();
		// 获取个人空间ID
		if (user == null) {
			userinfo.put("username", "");
			userinfo.put("roleName", "");
			userinfo.put("ip", "");
			userinfo.put("logintime", "");
			userinfo.put("id", "");
			userinfo.put("isadmin", "");
		} else {
			Map<String, Object> spaceInfo = baseService.Read("SELECT T.SPACE_ID, T.SPACES_IDENT, T.SPACES_NAME FROM ENGC_SPACES T WHERE T.USER_ID=? ",
					user.getUserid());
			userinfo.put("username", user.getUsername());
			userinfo.put("roleName", user.getRoleName());
			userinfo.put("ip", user.getIp());
			userinfo.put("logintime", user.getLogintime());
			userinfo.put("id", user.getUserid());
			userinfo.put("spaceId", spaceInfo.get("space_id"));
			userinfo.put("spacesIdent", spaceInfo.get("spaces_ident"));
			userinfo.put("spacesName", spaceInfo.get("spaces_name"));
		}

		return BaseUtils.getSuccessMessage(userinfo);
	}

	/**
	 * 获取当前登录人信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getCurrentUserOrgs")
	@ResponseBody
	public Map<String, Object> getCurrentUserOrgs(HttpServletRequest request) {
		SysUserInfo user = BaseUtils.getCurrentUser(request);
		// List<Map<String,Object>> usercurrentOrgs = user.getCurrentOrgs();
		List<Map<String, Object>> selectOrgs = new ArrayList<Map<String, Object>>();
		// for(Map<String,Object> temp:usercurrentOrgs){
		// Map<String,Object> tempselect = new HashMap<String,Object>();
		// tempselect.put("id", temp.get("orgid"));
		// tempselect.put("value", temp.get("orgid"));
		// tempselect.put("text", temp.get("orgname"));
		// selectOrgs.add(tempselect);
		// }
		return BaseUtils.getSuccessMessage(selectOrgs);
	}

	/**
	 * 设置当前登录人的当前OrgId
	 * 
	 * <pre>
	 * 方法 名 : setCurrentOrg
	 * 功能描述： 
	 * @param request
	 * @return
	 * 创 建 人: guzhixiong
	 * 日    期: 2013-5-29
	 * 修 改 人: 
	 * 日    期:
	 * </pre>
	 */
	@RequestMapping("/setCurrentOrg")
	@ResponseBody
	public Map<String, Object> setCurrentOrg(HttpServletRequest request) {
		String orgid = request.getParameter("orgid");
		String orgname = request.getParameter("orgname");
		if (BaseUtils.isEmpty(orgid) || BaseUtils.isEmpty(orgname)) {
			return BaseUtils.getErrorMessage("");
		} else {
			HttpSession session = request.getSession(true);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("orgid", orgid);
			map.put("orgname", orgname);
			session.setAttribute("currentOrg", map);
			return BaseUtils.getSuccessMessage("");
		}
	}
	
	
	@RequestMapping("/getCurOrgname")
	@ResponseBody
	public Map<String,String> getCurOrgname(HttpServletRequest request) {
		
		SysUserInfo info = (SysUserInfo) request.getSession().getAttribute(Constant.SYS_USER_INFO);
		String orgid = info.getOrgid();
		Map<String,String> returnMap = new HashMap<String, String>();
		
		String sql = "select orgname from stb_org where orgid=? ";
		List<Map<String,Object>> list = baseService.Query(sql, new Object[]{orgid});
		if(list==null || list.isEmpty()){
			returnMap.put("orgname", "");
		}
		returnMap.put("orgname",(String.valueOf(list.get(0).get("orgname"))));
		return returnMap;
	}
	

	/**
	 * 注销登录
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/doLoginOut")
	@ResponseBody
	public Map<String, Object> doLoginOut(HttpServletRequest request, HttpServletResponse response) {
		try {
			HttpSession session = request.getSession();
			session.invalidate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return BaseUtils.getSuccessMessage("");
	}

	/**
	 * 做一个跳转
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping("/doLogin")
	public String doLogin(HttpServletRequest req) {
		String url = req.getParameter("url");
		if (url == null || url.toString().equals("")) {
			return "/front/index";
		} else {
			Map<String, Object> userInfo = (Map<String, Object>) getCurrentUser(req).get("Data");
			Iterator iter = userInfo.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry pairs = (Map.Entry) iter.next();
				try {
					String value = pairs.getValue() + "";
					url = url.replaceAll("\\[" + pairs.getKey().toString() + "]", value);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return "redirect:" + url;
		}
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/doChangePassword")
	@ResponseBody
	public Map<String, Object> doChangePassword(HttpServletRequest request) {
		try {
			SysUserInfo curUser = BaseUtils.getCurrentUser(request);
			String OldPassword = request.getParameter("OldPassword");
			String NewPassword = request.getParameter("NewPassword");

			String sql = "select PASSWORD,TXTPASSWORD from stb_customer where usercode = ? ";
			List<Map<String, Object>> rows = baseService.Query(sql, new String[] { curUser.getUsercode() });
			if (rows == null || rows.isEmpty()) {
				throw new DBExecuteException("用户不存在");
			}
			Map userMap = rows.get(0);
			String oldpw = String.valueOf(userMap.get("password"));
			String txtpw = String.valueOf(userMap.get("txtpassword") == null ? "" : userMap.get("TXTPASSWORD"));

			if (!MD5Util.encodeByMD5(Constant.MD5_PWD_BYTE_LEN, OldPassword).equals(oldpw)) {
				return BaseUtils.getSuccessMessage("旧密码错误");
			}
			String[] params = null;
			if (txtpw.equals("")) {
				sql = "update stb_customer set password=? where usercode=? ";
				params = new String[] { MD5Util.encodeByMD5(Constant.MD5_PWD_BYTE_LEN, NewPassword), curUser.getUsercode() };
			} else {
				sql = "update stb_customer set password=?,TXTPASSWORD=?  where usercode=? ";
				params = new String[] { MD5Util.encodeByMD5(Constant.MD5_PWD_BYTE_LEN, NewPassword), NewPassword, curUser.getUsercode() };
			}
			baseService.Update(sql, params);
			return BaseUtils.getSuccessMessage("密码修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return BaseUtils.getSuccessMessage("密码修改失败");
		}

	}

	/**
	 * 系统校验
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/validate")
	@ResponseBody
	public boolean valiedate(HttpServletRequest request) {
		String action = request.getParameter("action");
		boolean rs = true;
		try {
			if ("exist".equalsIgnoreCase(action)) {
				rs = doValidateExist(request);
			}

		} catch (Exception e) {
			e.printStackTrace();
			rs = false;
		}
		return rs;
	}

	private boolean doValidateExist(HttpServletRequest request) {
		boolean result = false;
		String view = request.getParameter("view").toLowerCase();
		if ("user".equals(view)) {

		}
		if ("role".equals(view)) {

		}
		if ("menu".equals(view)) {

		}
		if ("dataprivate".equals(view)) {
			Map data = baseService.Read("select * from sys_dataprivate where dataview=?", request.getParameter("dataprivateview"));
			result = data == null || data.isEmpty() ? true : false;
		}
		return result;
	}

	public String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}
	
	
	
	@RequestMapping("/getOrgTree")
	@ResponseBody
	public List<Map<String, Object>> getOrgTree(HttpServletRequest request, String schoolOrgid) {
		String sql = "select orgid, orgname,fatherorgid,nodepath from stb_org where orgid like ?  and status=? order by nodepath , orgid ";
		List<Map<String, Object>> mapLs = baseService.Query(sql, new Object[] { schoolOrgid + "%",  Constant.VALID_YES });
		List<Map<String, Object>> topMap = new ArrayList<Map<String,Object>>();
		for (Map<String, Object> map : mapLs) {
			int childcount = 0;
			for (Map<String, Object> map2 : mapLs) {
				if (map2.get("fatherorgid") != null && String.valueOf(map2.get("fatherorgid")).equals(String.valueOf(map.get("orgid")))) {
					if(map.get("children")==null){
						map.put("children", new ArrayList<Map<String, Object>>());
					}
					childcount++;
					((ArrayList<Map<String, Object>>) map.get("children")).add(map2);
				}
			}
			if(childcount>0 && map.get("nodepath")!=null &&  Integer.parseInt(String.valueOf(map.get("nodepath")))==Constant.SCHOOL_NODEPATH ){
				topMap.add(map);
			}
		}
		return topMap;
	}
	

	@Resource
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	}
	
	
	
	
	public void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) throws Exception {
		final String userAgent = request.getHeader("USER-AGENT");
		try {
			String finalFileName = null;
			if (StringUtils.contains(userAgent, "MSIE")) {// IE浏览器
				finalFileName = URLEncoder.encode(fileName, "UTF8");
			} else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
				finalFileName = new String(fileName.getBytes(), "ISO8859-1");
			} else {
				finalFileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
			}
			// 这里设置一下让浏览器弹出下载提示框，而不是直接在浏览器中打开
			response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");
		} catch (UnsupportedEncodingException e) {
		}
	}
	
	@RequestMapping("/getAreaadmin_School")
	@ResponseBody
	public List<Map<String, Object>> getAreaadmin_School(HttpServletRequest request,String key){
		String sql = null;
		List<Map<String, Object>> record = null;
		String roleid = request.getParameter("roleid");
		if("1".equals(roleid)){//超级管理员
			if (null == key || "".equals(key)) {
				sql = "select t.bh id,t.xxmc text from stb_sr_org_school t left join stb_org o on t.bh = o.orgid where o.status = 1 ";
			}else{
				sql = "select t.bh id,t.xxmc text from stb_sr_org_school t left join stb_org o on t.bh = o.orgid where o.status = 1 and t.xxmc like '%"+key+"%'";
			}
			record = baseService.Query(sql);
		}
		if("2".equals(roleid)){//区域管理员
			if (null == key || "".equals(key)) {
				sql = "select t.bh id,t.xxmc text from stb_sr_org_school t left join stb_org o on t.bh = o.orgid where o.areano = ? and o.status = 1 ";
			}else{
				sql = "select t.bh id,t.xxmc text from stb_sr_org_school t left join stb_org o on t.bh = o.orgid where o.areano = ? and o.status = 1 and t.xxmc like '%"+key+"%'";
			}
			record = baseService.Query(sql, new Object[]{Integer.parseInt(BaseUtils.getCurrentUser(request).getDataOrgid())});
		}
		return record;
	}
	

}
